#!/bin/sh

SRCDIR="@top_srcdir@"
TEST_SRCDIR="${SRCDIR}/tests"
BUILDDIR="@top_builddir@"
TEST_BUILDDIR="${BUILDDIR}/tests"
PYTHON="@PYTHON_EXECUTABLE@"

PYTHON_SET=false
PRINT_MODE=false
while echo $1 | grep '^-' >/dev/null; do
    if [ "X$1" = "X--python" ]; then
	PYTHON_SET=true
    elif [ "X$1" = "X--print" ]; then
	PRINT_MODE=true
    elif [ "X$1" = "X--" ]; then
	break
    else
	echo "Unknown option: $1" 1>&2
	exit 1
    fi
    shift
done

if [ -z "$1" ]; then
    echo "No test given" 1>&2
    exit 1
fi

# See if we are skipping this test
T1=`basename $1`
if echo "$SKIP_TESTS" | grep -q "$T1"; then
    exit 77
fi

TEST=$1
shift

if [ -e "${TEST_BUILDDIR}/${TEST}" ]; then
    TEST="${TEST_BUILDDIR}/${TEST}"
elif [ -e "${TEST_SRCDIR}/${TEST}" ]; then
    TEST="${TEST_SRCDIR}/${TEST}"
else
    echo "Test ${TEST} not found" 1>&2
    exit 1
fi

if ${PYTHON_SET}; then
    PYTHON_MODE=true
elif echo "${TEST}" | grep '\.py$' >/dev/null; then
    PYTHON_MODE=true
else
    PYTHON_MODE=false
fi

if ${PYTHON_MODE}; then
    export PYTHONPATH="${BUILDDIR}/swig/python:${BUILDDIR}/swig/python/.libs:${BUILDDIR}/glib/swig/python:${BUILDDIR}/glib/swig/python/.libs:${BUILDDIR}/tcl/swig/python:${BUILDDIR}/tcl/swig/python/.libs:${TEST_BUILDDIR}"
    if [ ! -z "$MSYSTEM" ]; then
	# PYTHONPATH is separated by ; on windows
        export PYTHONPATH=`echo ${PYTHONPATH} | tr ':' ';'`
    fi
    TEST="${PYTHON} ${TEST}"
    export GENSIO_MEMTRACK=abort
else
    if [ ! -x ${TEST} ]; then
	echo "Test ${TEST} is not executable" 1>&2
	exit 1
    fi
fi

# We need to put the DLL in PATH for MSYS on Windows
if [ ! -z "$MSYSTEM" ]; then
    export PATH="${BUILDDIR}/lib:${BUILDDIR}/lib/.libs:${BUILDDIR}/glib/.libs:${BUILDDIR}/tcl/.libs:${BUILDDIR}/swig/python/.libs:$PATH"
else
    export LD_LIBRARY_PATH=${BUILDDIR}/lib:${BUILDDIR}/lib/.libs:${BUILDDIR}/glib/.libs:${BUILDDIR}/tcl/.libs:${BUILDDIR}/swig/python/.libs
fi
if test `uname` = Darwin; then
    TEST="DYLD_LIBRARY_PATH=${LD_LIBRARY_PATH} ${TEST}"
fi

if ${PRINT_MODE}; then
    echo export PYTHONPATH="${PYTHONPATH}"
    if [ ! -z "$MSYSTEM" ]; then
	echo export PATH="${PATH}"
    else
	echo export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}"
    fi
    echo ${TEST} $@
else
    # Run the test with each available OS handler
    for i in default @TCL_DIR@ @GLIB_DIR@; do
	echo "Testing with '$i'"
	export GENSIO_TEST_OS_HANDLER=$i
	parms=""
	for j in "$@"; do
	    parms="$parms '$j'"
	done
	eval "${TEST} $parms"
	rv=$?
	if test $rv != 0; then
	    # Test failed
	    exit $rv
	fi
    done
fi
